package com.sangmo.fts.restructure.aspect;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.fts.restructure.meta.TrainingApi;
import com.sangmo.fts.training.service.TrainingHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//@Component
//@Aspect
public class TrainingAspect {

    @Autowired
    private TrainingHelper helper;

//    @Around("@annotation(TrainingApi)")
    @Around("execution(* com.sangmo..api..*Api.*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        TrainingApi trainingApi = point.getTarget().getClass().getAnnotation(TrainingApi.class);
        if (null != trainingApi) {

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            Signature signature = point.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Object[] args = point.getArgs();

            for (int i = 0; i < methodSignature.getParameterNames().length; i++) {
                String name = methodSignature.getParameterNames()[i];
                if ("trainingId".equals(name)) {
                    Long trainingId = Long.valueOf(args[i].toString());
                    /*boolean canAccess = helper.checkAccess(trainingId);
                    if (!canAccess) {
                        throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.training.access.disabled");
                    }*/
                    //
                }
            }

        }

        return point.proceed();
    }
}
